package com.imoblife.brainwavestus.share;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.listener.AppRequestsListener;
import com.facebook.listener.FriendsRequestListener;
import com.facebook.listener.UpdateStatusListener;
import com.facebook.listener.UserRequestListener;
import com.imoblife.brainwavestus.R;
import com.imoblife.brainwavestus.share.SessionEvents.AuthListener;
import com.imoblife.brainwavestus.share.SessionEvents.LogoutListener;

public class LoginUtil {

	private Facebook mFb;
	private Handler mHandler;
	private SessionListener mSessionListener = new SessionListener();
	private String[] mPermissions;
	private Activity mActivity;
	private int mActivityCode;
	String share_url = "";
	String share_content = "";
	String share_title = "";
	String share_plugPackage = "";

	// private SharedPreferences mPref;

	public LoginUtil() {
	}

	public LoginUtil(Activity activity) {
		this.mActivity = activity;
	}

	public void init(final Activity activity, final int activityCode,
			final Facebook fb) {
		init(activity, activityCode, fb, new String[] {},"","","");
	}

	public void init(final Activity activity, final int activityCode,
			final Facebook fb, final String[] permissions, String shareUrl,
			String shareTitle, String shareContent) {
		mActivity = activity;
		mActivityCode = activityCode;
		mFb = fb;
		mPermissions = permissions;
		this.share_url = shareUrl;
		this.share_title = shareTitle;
		this.share_content = shareContent;
		
		mHandler = new Handler();

		SessionEvents.addAuthListener(mSessionListener);
		SessionEvents.addLogoutListener(mSessionListener);

		// mPref = mActivity.getPreferences(0);
		// String access_token = mPref.getString("access_token", null);
		// long expires = mPref.getLong("access_expires", 0);
		// if(access_token != null) {
		// mFb.setAccessToken(access_token);
		// }
		// if(expires != 0) {
		// mFb.setAccessExpires(expires);
		// }
	}

	public void loginAuthorize() {
		mFb.authorize(mActivity, mPermissions, mActivityCode,
				new LoginDialogListener());
	}

	public void logoutAuthorize() {
		SessionEvents.onLogoutBegin();
		AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFb);
		asyncRunner.logout(mActivity, new LogoutRequestListener());
	}

	public final class LoginDialogListener implements DialogListener {
		
		public void onComplete(Bundle values) {
			SessionEvents.onLoginSuccess();
			// SharedPreferences.Editor editor = mPref.edit();
			// editor.putString("access_token", mFb.getAccessToken());
			// editor.putLong("access_expires", mFb.getAccessExpires());
			// editor.commit();
			updateStatus();
		}

		
		public void onFacebookError(FacebookError error) {
			SessionEvents.onLoginError(error.getMessage());
		}

		
		public void onError(DialogError error) {
			SessionEvents.onLoginError(error.getMessage());
		}

		
		public void onCancel() {
			SessionEvents.onLoginError("Action Canceled");
		}
	}

	private class LogoutRequestListener extends BaseRequestListener {
		
		public void onComplete(String response, final Object state) {
			/*
			 * callback should be run in the original thread, not the background
			 * thread
			 */
			mHandler.post(new Runnable() {
				
				public void run() {
					SessionEvents.onLogoutFinish();
				}
			});
		}

		
		public void onFacebookError(FacebookError e, Object state) {
			

		}
	}

	private class SessionListener implements AuthListener, LogoutListener {

		
		public void onAuthSucceed() {
			SessionStore.save(mFb, mActivity);
		}

		
		public void onAuthFail(String error) {
		}

		
		public void onLogoutBegin() {
		}

		
		public void onLogoutFinish() {
			SessionStore.clear(mActivity);
		}
	}

	/**
	 * ���ֹ���
	 * 
	 */
	final static int PICK_EXISTING_PHOTO_RESULT_CODE = 1;
	private String graph_or_fql;

	/**
	 * ״̬���£�������Ϣ��ʱ���ߣ�
	 */
	public void updateStatus() {
		if (!Utility.mFacebook.isSessionValid()) {
			Util.showAlert(mActivity, "Warning", "You must first log in.");
		} else {
			Bundle params = new Bundle();
			params.putString("caption", share_title);
			params.putString("description",
					share_content);
			params.putString("link",share_url);
			params.putString("picture", "https://lh4.ggpht.com/ThMAvXHQsLW_0aFInM5S9FtAM5KVjMAaY0z5jwH6D0960HrTwA-4GaOfv_IG8TDXiA=w124");
			params.putString("name", mActivity.getString(R.string.share_action));

			Utility.mFacebook.dialog(mActivity, "feed", params,
					new UpdateStatusListener(mActivity));
			String access_token = Utility.mFacebook.getAccessToken();
			System.out.println(access_token);
		}
	}

	/**
	 * Ӧ������
	 */
	public void appRequest() {
		if (!Utility.mFacebook.isSessionValid()) {
			Util.showAlert(mActivity, "Warning", "You must first log in.");
		} else {
			Bundle params = new Bundle();
			params.putString("message",
					mActivity.getString(R.string.request_message));
			params.putString("redirect_uri", "http://www.baidu.com");
			Utility.mFacebook.dialog(mActivity, "apprequests", params,
					new AppRequestsListener(mActivity));
		}
	}

	/**
	 * ȡ�����ѵ���Ϣ������Ϣ�����ѵ�ʱ����
	 */
	public void getFriends() {
		if (!Utility.mFacebook.isSessionValid()) {
			Util.showAlert(mActivity, "Warning", "You must first log in.");
		} else {
			graph_or_fql = "graph";
			Bundle params = new Bundle();
			params.putString("fields", "name, picture, location");
			Utility.mAsyncRunner.request("me/friends", params,
					new FriendsRequestListener(mActivity, graph_or_fql));
		}
	}

	/**
	 * �ϴ���Ƭ
	 */
	public void updatePhoto() {
		if (!Utility.mFacebook.isSessionValid()) {
			Util.showAlert(mActivity, "Warning", "You must first log in.");
		} else {
			Intent intent = new Intent(Intent.ACTION_PICK,
					(MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
			mActivity.startActivityForResult(intent,
					PICK_EXISTING_PHOTO_RESULT_CODE);
		}
	}

	/**
	 * ���?ǰλ��
	 */
	public void currentPlaceCheckIn() {
		if (!Utility.mFacebook.isSessionValid()) {
			Util.showAlert(mActivity, "Warning", "You must first log in.");
		} else {
			final Intent myIntent = new Intent(
					mActivity.getApplicationContext(), Places.class);
			myIntent.putExtra("LOCATION", "current");
			mActivity.startActivity(myIntent);
		}

	}

	/*
	 * Request user name, and picture to show on the main screen.
	 */

	public void requestUserData() {
		Bundle params = new Bundle();
		params.putString("fields", "name, picture , email");
		Utility.mAsyncRunner.request("me", params, new UserRequestListener(
				mActivity));
	}
}
